/**
 * @file url相关api
 */

import { isString, isEmpty, isArray } from '../core/types'
import { httpReg, doubleSlashReg } from '../core/regexp'

/**
 * 格式化路径没有//或者http(s)开头，就加上
 * @param {string} src - 需要转换的src路径
 * @param {string} [pre='//'] - 需要在路径前添加的字符，默认为 //
 * @returns {string} 第一个字符
 */
export const formatUrlPrefix = (src, pre = '//') => {
  if (isEmpty(src)) return ''
  if (!isString(src)) return ''
  if (httpReg.test(src) || doubleSlashReg.test(src)) return src
  return `${pre}${src}`
}

/**
 * url参数 => 对象
 * @param  {string} [url = window.location.href]  default: window.location.href
 * @return {object}
 *
 * @example
 * parseQueryString('www.baidu.com?id=1&name=tom') // => {id: "1", name: "tom"}
 * parseQueryString('www.baidu.com?') // => {}
 */
export const parseQueryString = url => {
  url = isEmpty(url) ? window.location.href : url
  if (url.indexOf('?') === -1) {
    return {}
  }
  const search = url[0] === '?' ? url.substr(1) : url.substring(url.lastIndexOf('?') + 1)
  if (search === '') {
    return {}
  }
  const searchArr = search.split('&')
  const query = {}
  for (let i = 0; i < searchArr.length; i++) {
    const pair = searchArr[i].split('=')
    query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
  }
  return query
}

/**
 * 对象 => url参数
 * @param  {object} obj
 * @return {string}
 *
 * @example
 * stringfyQueryString({id: 1, name: 'tom'}) // => 'id=1&name=tom'
 * stringfyQueryString({}) // => ''
 * stringfyQueryString() // => ''
 */
export const stringfyQueryString = obj => {
  if (isEmpty(obj)) return ''
  const pairs = []

  for (const key in obj) {
    const value = obj[key]

    if (isArray(value)) {
      for (let i = 0; i < value.length; ++i) {
        pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]))
      }
      continue
    }

    pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
  }

  return pairs.join('&')
}

/**
 * 获取URL参数中某个属性的值
 * @param {string} key 要取值的属性名
 * @returns {string | null} url中该参数的值
 *
 * @example
 * window.location.href = 'www.baidu.com?name=tom'
 * getQueryByKey('name') // => 'tom'
 * getQueryByKey('age') // => ''
 * getQueryByKey('') // => ''
 */
export const getQueryByKey = (key, href) => {
  const query = href?.split('?')[1] || window.location.href.split('?')[1] || ''
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    if (pair[0] == key) {
      return pair[1]
    }
  }
  return null
}
